package com.mars.common;

import com.mars.exception.ParamException;
import com.mars.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理的捕获
 * Created by MARS on 2017/12/21.
 */

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        //获取当前url
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        //全局默认异常信息提示
        String defaultMsg = "System error";

        //数据请求 和 页面请求 异常处理
        // .json  .page
        if (url.endsWith(".json")) {
            //如果异常的类型 与 自定义的异常类型一致，则抛出
            if (e instanceof PermissionException || e instanceof ParamException) {
                JsonData result = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());
            } else {
                log.error("unknown json  exception ,url :"+url,e);
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView",result.toMap());
            }
        } else if(url.endsWith(".page")) {
            log.error("unknown page  exception ,url :"+url,e);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception",result.toMap());
        } else {
            log.error("unknown exception ,url :"+url,e);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView",result.toMap());
        }

        return mv;
    }
}
